package com.tanjie.blackbean.web.advice;

import cn.hutool.core.util.StrUtil;
import com.tanjie.blackbean.web.annotation.WrapResponse;
import com.tanjie.blackbean.pojo.exception.AuthException;
import com.tanjie.blackbean.pojo.exception.BizException;
import com.tanjie.blackbean.pojo.response.BlackBeanResponse;
import com.tanjie.blackbean.pojo.response.ExceptionCode;
import com.tanjie.blackbean.pojo.response.IResult;
import com.tanjie.blackbean.pojo.response.ResponseBean;
import com.tanjie.blackbean.web.support.AnnotationExtractor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.dao.DataAccessException;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConversionException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 异常拦截处理
 *
 * @author: tanjie
 * @date: 2022-03-31
 **/
@Slf4j
@RestControllerAdvice
public class ExceptionHandleAdvice {

    /**
     * 请求参数绑定异常
     *
     * @param handler 接口处理方法
     * @param e       异常对象
     * @return 接口返回的内容
     */
    @ExceptionHandler({BindException.class})
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseBean bindExceptionHandler(HandlerMethod handler, BindException e) {
        log.error("请求参数绑定异常: {}", e.getMessage());
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> messageList = fieldErrors.stream()
                .map(DefaultMessageSourceResolvable::getDefaultMessage)
                .collect(Collectors.toList());
        WrapResponse wrapResponse = AnnotationExtractor.get(handler, WrapResponse.class);
        if (wrapResponse != null) {
            ResponseBean responseBean = createResponse(wrapResponse, ExceptionCode.BIND_EXCEPTION, messageList);
            if (responseBean != null) return responseBean;
        }

        return new BlackBeanResponse(ExceptionCode.BIND_EXCEPTION, messageList);
    }

    /**
     * 消息转换异常
     *
     * @param handler 接口请求方法
     * @param e       异常对象
     * @return 接口返回的内容
     */
    @ExceptionHandler(value = HttpMessageConversionException.class)
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public ResponseBean httpMessageNotReadableExceptionHandler(HandlerMethod handler, HttpMessageConversionException e) {
        log.error("消息转换异常: {}", e.getMessage());
        e.printStackTrace();
        WrapResponse wrapResponse = AnnotationExtractor.get(handler, WrapResponse.class);
        String message = e.getMessage();
        if (e instanceof HttpMessageNotReadableException) {
            if (StrUtil.isNotBlank(message)) {
                assert message != null;
                String[] messageArray = message.split(";");
                message = messageArray[0];
            }
        }

        if (wrapResponse != null) {
            ResponseBean responseBean = createResponse(wrapResponse, ExceptionCode.HTTP_MESSAGE_CONVERSION_EXCEPTION, message);
            if (responseBean != null) return responseBean;
        }

        return new BlackBeanResponse(ExceptionCode.HTTP_MESSAGE_CONVERSION_EXCEPTION, message);
    }

    @ExceptionHandler(BizException.class)
    @ResponseStatus(HttpStatus.OK)
    public ResponseBean bizExceptionHandler(HandlerMethod handler, BizException e) {
        IResult bizErrorCode = e.getBizErrorCode();
        String message = e.getMessage();
        log.error("业务逻辑异常: {},{}", bizErrorCode.getMessage(), message);
        WrapResponse wrapResponse = AnnotationExtractor.get(handler, WrapResponse.class);
        if (wrapResponse != null) {
            ResponseBean responseBean = createResponse(wrapResponse, bizErrorCode, message);
            if (responseBean != null) return responseBean;
        }
        return new BlackBeanResponse(bizErrorCode, message);
    }

    @ExceptionHandler(AuthException.class)
    @ResponseStatus(HttpStatus.UNAUTHORIZED)
    public ResponseBean authExceptionHandler(HandlerMethod handler, AuthException e) {
        IResult bizErrorCode = e.getBizErrorCode();
        String message = e.getMessage();
        log.error("认证授权异常: {},{}", bizErrorCode.getMessage(), message);
        WrapResponse wrapResponse = AnnotationExtractor.get(handler, WrapResponse.class);
        if (wrapResponse != null) {
            ResponseBean responseBean = createResponse(wrapResponse, bizErrorCode, message);
            if (responseBean != null) return responseBean;
        }
        return new BlackBeanResponse(bizErrorCode, message);
    }

    @ExceptionHandler(DataAccessException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseBean SQLExceptionHandler(HandlerMethod handler, DataAccessException e) {
        log.error("数据访问发生异常");
        e.printStackTrace();
        WrapResponse wrapResponse = AnnotationExtractor.get(handler, WrapResponse.class);
        if (wrapResponse != null) {
            ResponseBean responseBean = createResponse(wrapResponse, ExceptionCode.EXECUTE_SQL_ERROR, e);
            if (responseBean != null) return responseBean;
        }
        return new BlackBeanResponse(ExceptionCode.EXECUTE_SQL_ERROR, e.getMessage());

    }

    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public ResponseBean notPredictExceptionHandler(HandlerMethod handler, Exception e) {
        log.error("系统内部未预知异常: {}", e.getMessage());
        e.printStackTrace();
        WrapResponse wrapResponse = AnnotationExtractor.get(handler, WrapResponse.class);
        if (wrapResponse != null) {
            ResponseBean responseBean = createResponse(wrapResponse, ExceptionCode.NOT_PREDICT, e);
            if (responseBean != null) return responseBean;
        }
        return new BlackBeanResponse(ExceptionCode.NOT_PREDICT, e.getMessage());
    }

    @ExceptionHandler(NoHandlerFoundException.class)
    @ResponseStatus(HttpStatus.NOT_FOUND)
    public ResponseBean noHandlerFoundExceptionHandler(NoHandlerFoundException e) {
        log.error("NoHandlerFoundException: {}", e.getMessage());
        e.printStackTrace();
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes instanceof HttpServletRequest) {
            // 获取request对象
            HttpServletRequest request = (HttpServletRequest) requestAttributes;
            log.info("IP             : {}", request.getRemoteAddr());
        }
        log.error("404没找到请求:{}", e.getMessage());
        return new BlackBeanResponse(ExceptionCode.NO_HANDLER_FOUND_EXCEPTION);
    }

    private ResponseBean createResponse(WrapResponse wrapResponse, IResult result, Object data) {
        Class<? extends ResponseBean> resultType = wrapResponse.responseType();
        try {
            ResponseBean responseBean = resultType.newInstance();
            responseBean.create(result, data);
            return responseBean;
        } catch (InstantiationException | IllegalAccessException e) {
            e.printStackTrace();
        }
        return null;
    }

}
